function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    return response;
  } else if (response.status === 401) {
    // console.log('401 auth error');
    const error = new Error(response.statusText);
    error.response = response;
    throw error;
  } else {
    const error = new Error(response.statusText);
    error.response = response;
    throw error;
  }
}

function parseJSON(response) {
  return response.json();
}

export function request(url, options, callback) {
  const opt = options || {};
  return fetch(url, opt)
    .then(checkStatus)
    .then(parseJSON)
    .then(data => (callback(data)))
    .catch(err => (err));
}
// get
export function GET(url, callback) {
  const options = {
    mode: 'cors',
    method: 'PUT',
    credentials: 'omit',
  };
  request(url, options, callback);
}
// post body={}
export function POST(url, body, callback) {
  const options = {
    mode: 'cors',
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    credentials: 'omit',
    body,
  };
  request(url, options, callback);
}

export default { request, GET, POST };
